package cn.com.text;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import org.litepal.crud.DataSupport;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import cn.com.text.Activity.MyPostActivity;
import cn.com.text.Dao.News;
import cn.com.text.Dao.User;
import cn.com.text.Util.ImageHelper;
import cn.com.text.Util.MySQLConnections;

import static android.content.ContentValues.TAG;
import static java.lang.Thread.sleep;

/**
 * Created by 86176 on 2021/12/20.
 */

public class NewsTitleFragment extends Fragment {
    private User user;
    private boolean isTwoPane;
    private static Connection conn = null;
    private static PreparedStatement stmt = null;
    private List<News> sNewsList = new ArrayList<News>();
    private static final CountDownLatch ctl = new CountDownLatch(1);
    private SwipeRefreshLayout swipeRefreshLayout;
    private NewsAdapter newsAdapter = new NewsAdapter();
    private boolean flag = false;//子线程刷新结束标志

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news_title_frag, container, false);
        RecyclerView newsTitleRecyclerView = (RecyclerView) view.findViewById(R.id.news_title_recycle_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()) {
            @Override
            protected int getExtraLayoutSpace(RecyclerView.State state) {
                return 300;
            }
        };

        newsTitleRecyclerView.setLayoutManager(layoutManager);
        @SuppressLint("HandlerLeak") final
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                sNewsList = (List<News>) msg.obj;
                Log.d("sNewList.length : ", String.valueOf(sNewsList.size()));
            }
        };
        Thread thread = null;
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    conn = MySQLConnections.getConnection("blog");

                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    String sql = "select id,author,title,content,image from Blog";
                    List<News> list_tmp = new ArrayList<News>();
                    if (conn != null) {
                        stmt = conn.prepareStatement(sql);
                        conn.setAutoCommit(false);
                        ResultSet rs = stmt.executeQuery();//用rs接收sql语句返回的查询结果
                        //执行查询语句并且保存结果
                        while (rs.next()) {
                            News news = new News();
                            news.setId(Integer.parseInt(rs.getString("id")));
                            news.setAuthor(rs.getString("author"));
                            news.setTitle(rs.getString("title"));
                            news.setContent("\u3000\u3000" + rs.getString("content"));
                            news.setImage(rs.getString("image"));
                            Log.d("Title", news.getTitle());
                            list_tmp.add(news);
                        }
                        Collections.reverse(list_tmp);
                        sNewsList = list_tmp;
                        Message msg = new Message();
                        msg.obj = list_tmp;
                        handler.sendMessage(msg);
                        rs.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                }
            }
        });
        thread.start();

        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swip_refresh);
//        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                refreshContent();
//
//                newsAdapter.addList(sNewsList);
//                swipeRefreshLayout.setRefreshing(false);
//                Log.d("sNewList.length : ", String.valueOf(sNewsList.size()));
//            }
//        });
        newsAdapter.setmNewList(sNewsList);
        newsTitleRecyclerView.setAdapter(newsAdapter);
        return view;
    }

    private void refreshContent() {
        @SuppressLint("HandlerLeak") final
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
//                sNewsList.add((News) msg.obj);

            }
        };
        Thread thread = null;
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                List<News> list_tmp = new ArrayList<News>();
                try {
                    conn = MySQLConnections.getConnection("blog");

                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    String sql = "select id,author,title,content,image from Blog";

                    if (conn != null) {
                        stmt = conn.prepareStatement(sql);
                        conn.setAutoCommit(false);
                        ResultSet rs = stmt.executeQuery();//用rs接收sql语句返回的查询结果
                        //执行查询语句并且保存结果
                        while (rs.next()) {
                            News news = new News();
                            news.setId(Integer.parseInt(rs.getString("id")));
                            news.setAuthor(rs.getString("author"));
                            news.setTitle(rs.getString("title"));
                            news.setContent("\u3000\u3000" + rs.getString("content"));
                            news.setImage(rs.getString("image"));
                            Message msg = new Message();
                            msg.obj = news;
                            handler.sendMessage(msg);
                            list_tmp.add(news);
                        }
                        flag = true;
                        rs.close();

                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                sNewsList = list_tmp;
            }
        });
        thread.start();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity().findViewById(R.id.new_content_layout) != null) {
            isTwoPane = true;
        } else {
            isTwoPane = false;
        }
    }

    class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
        private List<News> mNewsList = new ArrayList<News>();
        private LayoutInflater mInflater;

        public void addList(List<News> sNewsListTmp) {
            sNewsList.addAll(sNewsList);
            sNewsList.removeAll(sNewsList);
            sNewsList.addAll(sNewsListTmp);
            notifyDataSetChanged();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView newsTitleText;
            CardView newsCardView;
            TextView newsContentPreView;
            ImageView imageViewPreView;
            TextView newsUserName;
            public ViewHolder(View view) {
                super(view);
                newsCardView = (CardView) view.findViewById(R.id.item_cardview);
                newsTitleText = (TextView) view.findViewById(R.id.news_title);
                newsContentPreView = (TextView) view.findViewById(R.id.news_contentPre);
                imageViewPreView = (ImageView) view.findViewById(R.id.imagePreRandon);
                newsUserName = (TextView) view.findViewById(R.id.news_user);
            }
        }

        public NewsAdapter() {
        }

        public void setmNewList(List<News> list) {
            this.mNewsList = list;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_item, parent, false);
            final ViewHolder holder = new ViewHolder(view);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    News news = mNewsList.get(holder.getAdapterPosition());
                    if (isTwoPane) {
                        NewsContentFragment newsContentFragment = (NewsContentFragment) getFragmentManager()
                                .findFragmentById(R.id.news_content_fragment);
                        newsContentFragment.refresh(news.getTitle(), news.getContent());
                    } else {
                        NewsContentActivity.actionStart(getActivity(), news.getTitle(), news.getContent(), news.getImage());
                    }
                }
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            News news = mNewsList.get(position);
            holder.newsTitleText.setText(news.getTitle());
            holder.newsContentPreView.setText(news.getContent().substring(0, (news.getContent().length() > 10 ? 10 : news.getContent().length() / 2)));
            holder.imageViewPreView.setImageBitmap(ImageHelper.stringToBitmap(news.getImage()));
            List<User> userList = DataSupport.findAll(User.class);
            String postUser = null;
            if(userList.size()!=0){
                postUser = userList.get(0).getName();
            }
            holder.newsUserName.setText(postUser);
        }

        @Override
        public int getItemCount() {
            return mNewsList.size();
        }
    }
}
